<template>
  <div class="message_container">
    <div class="message_wrapper">
      <div class="cancel" @click="cancelClick">
        <CloseOutlined />
      </div>
      <div class="mes_content">
        <div class="mes_left">
          <div class="left_title">
            <a-tabs v-model:activeKey="activeKey">
              <a-tab-pane key="true" tab="咨询">
                <div style="transform: translateY(-15px);">
                  <div class="itemBox" :class="{ isActive: chatsStore.currentChat === item.roomId }"
                    @click="itemClick(item)" v-for="(item) in chatsStore.chats" :key="item.roomId">
                    <ChatItem :data="item" />
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="false" tab="沟通">
                <div style="transform: translateY(-15px);">
                  <div class="itemBox" :class="{ isActive: chatsStore.currentChat === item.roomId }"
                    @click="itemClick(item)" v-for="(item) in chatsStore.chats" :key="item.roomId">
                    <ChatItem :data="item" />
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
        <div class="mes_right">
          <div class="right_title">通知消息</div>
          <div class="chat_detail" ref="containerRef" @scroll="onChatScroll">
            <chat />
          </div>
          <div class="message_sent">
            <div class="mes_box">
              <textarea v-model="messageText" placeholder="输入消息..." id="textInput"></textarea>
            </div>
            <div class="btnBox">
              <button @click="sendMessage">发送</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue';
import ChatItem from './cpm/chatItem.vue';
import { CloseOutlined } from '@ant-design/icons-vue';
import { useMessageStore } from '@/stores/module/message';
import { useChatsStore } from '@/stores/module/chats/chats';
import { sentMes } from '@/service/module/message/message';
import { MesEnum } from '@/constants';
import chat from './cpm/chat.vue';
import { MesConnect } from '@/utils/ws/wsMes';

MesConnect()
const messageStore = useMessageStore();
const chatsStore = useChatsStore()
const roomId = computed(() => {
  return chatsStore.currentChat
})
const cancelClick = () => {
  messageStore.showMessage = false
}
const activeKey = computed({
  get: () => chatsStore.activeKey,
  set: (val) => { chatsStore.activeKey = val }
});



watch(activeKey, async (val) => {
  if (val) {
    await chatsStore.getChatsList(activeKey.value)
    chatsStore.messageList = []
    chatsStore.currentChat = ''
    if (chatsStore.goSellerId && chatsStore.goSellerId.length > 0) {
      chatsStore.currentChat = chatsStore.goSellerId
      chatsStore.goSellerId = ''
    }
  }
}, { immediate: true })

const itemClick = (item) => {
  chatsStore.currentChat = item.roomId
  chatsStore.talkInfo = item
}
watch(roomId, async (newId) => {
  await chatsStore.getMesList(newId, '')
  messageText.value = ''
  // MesConnect()
})

//聊天消息
const messageText = ref()
const sendMessage = async () => {
  await sentMes(roomId.value, MesEnum.Txet, messageText.value)
  messageText.value = ''
}

const containerRef = ref();

watch(
  () => chatsStore.messageList,
  () => {
    nextTick(() => {
      if (containerRef.value) {
        containerRef.value.scrollTop = containerRef.value.scrollHeight;
      }
    });
  },
  { deep: true, immediate: true }
);

const onChatScroll = async (e: Event) => {
  const target = e.target as HTMLElement;
  if (target.scrollTop === 0 && chatsStore.chats.length > 0) {
    // 记录加载前的高度
    const oldScrollHeight = target.scrollHeight;
    const oldScrollTop = target.scrollTop;

    // 取第一条数据的id（假设是messageList[0].message.id）
    const firstId = chatsStore.messageList[0].message.id;
    await chatsStore.getMesMoreList(roomId.value, firstId);

    // 等待DOM更新
    nextTick(() => {
      const newScrollHeight = target.scrollHeight;
      // 保持原有内容位置
      target.scrollTop = newScrollHeight - oldScrollHeight + oldScrollTop;
    });
  }
};
</script>

<style lang="less" scoped>
@import '../../../src/assets/css/primary/index.less';

.message_container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 1180px;
  min-width: 1180px;
  display: flex;
  justify-content: center;
  align-items: center;


  .message_wrapper {
    background-color: #fff;
    border-radius: 18px;
    width: 80vw;
    height: 50vw;
    max-width: 1080px;
    max-height: 720px;
    min-width: 1080px;
    min-height: 720px;
    display: flex;
    flex-direction: column;
    position: relative;

    .cancel {
      position: absolute;
      top: 8px;
      right: 8px;
      cursor: pointer;
      z-index: 99;
    }

    .mes_content {
      display: flex;
      flex: 1;

      .mes_left {
        flex: 1;

        .left_title {
          height: 40px;
          line-height: 40px;
          text-align: center;
          font-size: 18px;

          :deep(.ant-tabs-nav-wrap) {
            width: 100%;

          }

          :deep(.ant-tabs-nav-list) {
            width: 100%;
          }

          :deep(.ant-tabs-tab) {
            width: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }

      .mes_right {
        width: 810px;
        flex-wrap: wrap;
        flex: 3;
        border-bottom-right-radius: 18px;
        border-top-right-radius: 18px;
        background-color: #f2f2f2;
        display: flex;
        flex-direction: column;
        position: relative;

        .right_title {
          height: 47px;
          line-height: 47px;
          padding: 0 36px;
          font-size: 18px;
          border-bottom: 1px solid #e8e8e8;
        }

        .chat_detail {
          width: 100%;
          height: 550px;
          overflow: auto; // 保持
        }

        .message_sent {
          width: 100%;
          // position: absolute;
          // bottom: 0px;
          border-top: 1px solid #ddd;
          display: flex;
          flex-direction: column;


          .mes_box {
            width: 100%;
            height: 120px;
            padding: 0 5px;

            #textInput {
              box-sizing: border-box;
              width: 97%;
              padding: 10px;
              border: 1px solid transparent;
              border-radius: 4px;
              background-color: #f2f2f2;
              outline: none;
              font-size: 16px;
              resize: none;
              height: 78px;
              transition: border-color 0.3s;
            }

            #textInput::-webkit-scrollbar {
              display: none;
            }

            #textInput {
              -ms-overflow-style: none;
              scrollbar-width: none;
            }
          }

          .btnBox {
            width: 100%;
            position: absolute;
            bottom: 0;
            height: 40px;

            button {
              width: 68px;
              height: 26px;
              position: absolute;
              bottom: 5px;
              right: 8px;
              background-color: @primary-color;
              outline: none;
              border: none;
              border-radius: 13px;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
}

.isActive {
  background-color: #e8e8e8;
}
</style>
